/**
 * Project Name:mauto-web
 * File Name:PeopleController.java
 * Package Name:com.inftech.mauto.sys.web
 * Date:2016年11月9日下午12:25:36
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.sys.web.front;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.inftech.mauto.common.base.BaseController;
import com.inftech.mauto.common.base.BusinessException;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.common.utils.Base64ToPic;
import com.inftech.mauto.common.utils.CommonUtils;

/**
 * ClassName:ApiFileController <br/>
 * Function: 文件相关控制层. <br/>
 * Date: 2016年11月9日 下午12:25:36 <br/>
 * 
 * @author puyf
 * @version
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/api/file")
public class ApiFileController extends BaseController {
	
	/**
	 * 后台服务器路径
	 */
	@Value("${filePath}")
	private String filePath;

	/**
	 * 
	 * upload:上传图片. <br/>
	 *
	 * @author puyf
	 * @param request
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	@RequestMapping(value = "/upload", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String upload(@RequestBody String requestStr, HttpServletRequest request) throws Exception {
		String outJson = "";
		try {
			JSONObject jsonObject = (JSONObject) JSONObject.parse(requestStr);
			// 图片base64字符串
			String image = jsonObject.getString("image");
			String tempPath = filePath+"temp";
			File tempDir = new File(tempPath);
			if (!tempDir.exists() && !tempDir.isDirectory()) {
				// 目录不存在
				tempDir.mkdir();
			}
			String fileName = CommonUtils.getNowL() + ".jpg";
			String filePath = tempPath + "/" + fileName;
			Base64ToPic.GenerateImage(image, filePath);
			LOG.info("上传图片成功");
			// 返回结果
			HttpStatusCodeEnum statusCode = HttpStatusCodeEnum.STATUS_CODE_200;
			outJson = getOutJson(statusCode, true, statusCode.toString(), "temp/" + fileName);
		} catch (Exception e) {
			if (e instanceof BusinessException) {
				throw e;
			}
			LOG.error("上传图片失败", e);
			HttpStatusCodeEnum statusCode = HttpStatusCodeEnum.SCOPE_BASE;
			outJson = getOutJson(statusCode, false, statusCode.toString(), null);
		}
		return outJson;
	}
}
